package com.neudu.yiyang.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.utils.TokenUtils;
import com.neudu.yiyang.pojo.User;
import com.neudu.yiyang.service.MenuService;
import com.neudu.yiyang.service.UserService;
import com.neudu.yiyang.utils.FLAGS;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    JSONReturn jsonReturn;
    @Autowired
    MenuService menuService;
    @Autowired
    UserService userService;
    @Autowired
    TokenUtils tokenUtils;

    @RequestMapping("login")
    public String login(User user, HttpServletRequest request){
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername())
                    .eq(User::getPassword, user.getPassword())
                    .select(User::getId, User::getNickname, User::getUsername, User::getRoleId);
            List<User> users = userService.list(queryWrapper);
            System.out.println(users);

            if (users != null && users.size() > 0){
                User loginuser = users.get(0);
                Integer userId = loginuser.getId();
                System.out.println("idididididididididid"+userId);
                String token = tokenUtils.getToken(userId);
                loginuser.setToken(tokenUtils.getToken(userId));
                loginuser.setToken(token);
                return jsonReturn.returnSuccess(loginuser);
            } else {
                    return jsonReturn.returnFailed(FLAGS.LOGIN_FAIL);
            }
        } catch(Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }


    //注册功能
    @RequestMapping("register")
    public String register(User user) throws JsonProcessingException {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            List<User> users = userService.list(queryWrapper);
            if (users != null && users.size() > 0) {
                return jsonReturn.returnFailed(FLAGS.RETURN_FAILED);
            } else {
                user.setCreateTimeBeforeInsert();
                userService.save(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonReturn.returnSuccess();
    }

    //查询用户信息
    @RequestMapping("listusers")
    public String listusers(User conds) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(conds.getUsername()), User::getUsername, conds.getUsername())
                    .eq(!ObjectUtils.isEmpty(conds.getPassword()),User::getPassword, conds.getPassword())
                    .eq(!ObjectUtils.isEmpty(conds.getNickname()),User::getNickname, conds.getNickname())
                    .eq(!ObjectUtils.isEmpty(conds.getSex()),User::getSex, conds.getSex())
                    .eq(!ObjectUtils.isEmpty(conds.getEmail()),User::getEmail, conds.getEmail())
                    .eq(!ObjectUtils.isEmpty(conds.getPhoneNumber()),User::getPhoneNumber, conds.getPhoneNumber())
                    .select(User::getId, User::getNickname, User::getUsername, User::getRoleId);
            List<User> users = userService.list(queryWrapper);
            return jsonReturn.returnSuccess(users);
        }catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }

    }

    @RequestMapping("get_all_users")
    public String getAllUsers(@RequestBody PageInfo pageInfo)  {
        try {
            PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
            List<User> users = userService.list();
            PageInfo<User> pageInfo1 = new PageInfo<>(users);
            return jsonReturn.returnSuccess(pageInfo1);
        }catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_users_by")
    public String getUserBy(@RequestBody User user){
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(user.getId()), User::getId, user.getId())
                    .eq(!ObjectUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername())
                    .eq(!ObjectUtils.isEmpty(user.getPassword()), User::getPassword, user.getPassword())
                    .like(!ObjectUtils.isEmpty(user.getNickname()), User::getNickname, user.getNickname());
            List<User> users = userService.list(queryWrapper);
            return jsonReturn.returnSuccess(users);
        }catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_user_by")
    public String getUserBy(@RequestParam("id") Integer id) {
        try {
            User user = userService.getById(id);
            return jsonReturn.returnSuccess(user);
        }catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("add_one_user")
    public String addOneUser(@RequestBody User user) {
        try {
            user.setCreateTimeBeforeInsert(); // 原有创建时间逻辑
            user.setCreateBy(1); // 新增时创建者设为1
            user.setUpdateBy(1); // 新增时更新者设为1（首次更新）

            // 密码默认值逻辑（原有）
            if (StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(user.getUsername());
            }

            userService.save(user);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 修改用户时强制设置update_by为1
    @RequestMapping("update_one_user")
    public String updateOneUser(@RequestBody User user) {
        try {
            user.setUpdateTime(new Date()); // 原有更新时间逻辑
            user.setUpdateBy(1); // 修改时更新者设为1

            // 保留原密码逻辑（原有）
            User originalUser = userService.getById(user.getId());
            if (StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(originalUser.getPassword());
            }

            userService.updateById(user);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("delete_userbyid")
    public String deleteOneUser(@RequestParam("id") Integer id) {
        try {
            userService.removeById(id);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("get_current_user_info")
    public String getCurrentUserInfo(HttpServletRequest request) throws JsonProcessingException {
        System.out.println("获取当前用户信息");
        try {
            String tokenHeader = request.getHeader("Authorization");
            if (tokenHeader == null || !tokenHeader.startsWith("Bearer ")) {
                return jsonReturn.returnFailed("未携带有效 Token");
            }

            String token = tokenHeader.substring(7);
            Algorithm algorithm = Algorithm.HMAC256(tokenUtils.getSecretKey());

            // 使用 Auth0 库解析 Token
            DecodedJWT decodedJWT = JWT.require(algorithm)
                    .build()
                    .verify(token); // 验证签名并解析 Token

            Integer userId = decodedJWT.getClaim("userId").asInt(); // 从负载中获取 userId
            System.out.println("解析到的用户 ID: " + userId); // 关键日志
            User user = userService.getById(userId);
            System.out.println("查询到的用户信息: " + user); // 确认用户是否存在
            if (user == null) {
                return jsonReturn.returnFailed("用户不存在");
            }
            return jsonReturn.returnSuccess(user);
        } catch (Exception e) {
            e.printStackTrace();
            // 区分 Token 过期和其他错误
            if (e instanceof com.auth0.jwt.exceptions.TokenExpiredException) {
                return jsonReturn.returnFailed("token expired");
            }
            return jsonReturn.returnError("Token 验证失败：" + e.getMessage());
        }
    }

    @RequestMapping("update_by_user")
    public String updateByUser(@RequestBody User user, HttpServletRequest request) {
        try {
            // 从请求头中获取 Token
            String tokenHeader = request.getHeader("Authorization");
            if (tokenHeader == null || !tokenHeader.startsWith("Bearer ")) {
                return jsonReturn.returnFailed("未携带有效 Token");
            }
            String token = tokenHeader.substring(7);
            Algorithm algorithm = Algorithm.HMAC256(tokenUtils.getSecretKey());
            // 使用 Auth0 库解析 Token
            DecodedJWT decodedJWT = JWT.require(algorithm)
                    .build()
                    .verify(token);
            Integer userId = decodedJWT.getClaim("userId").asInt();

            // 检查用户是否存在
            User originalUser = userService.getById(userId);
            if (originalUser == null) {
                return jsonReturn.returnFailed("用户不存在");
            }
            // 检查两次输入的密码是否一致
            if (!StringUtils.isEmpty(user.getPassword()) &&!StringUtils.isEmpty(user.getConfirmPassword())
                    &&!user.getPassword().equals(user.getConfirmPassword())) {
                return jsonReturn.returnFailed("两次输入的密码不一致");
            }
            // 更新非空字段
            if (!StringUtils.isEmpty(user.getNickname())) {
                originalUser.setNickname(user.getNickname());
            }
            if (!StringUtils.isEmpty(user.getPassword())) {
                originalUser.setPassword(user.getPassword());
            }
            if (user.getSex() != null) {
                originalUser.setSex(user.getSex());
            }
            if (!StringUtils.isEmpty(user.getEmail())) {
                originalUser.setEmail(user.getEmail());
            }
            if (!StringUtils.isEmpty(user.getPhoneNumber())) {
                originalUser.setPhoneNumber(user.getPhoneNumber());
            }
            // 设置更新时间和更新者
            originalUser.setUpdateTime(new Date());
            originalUser.setUpdateBy(1);
            // 执行更新操作
            boolean success = userService.updateById(originalUser);
            if (success) {
                return jsonReturn.returnSuccess("用户信息更新成功");
            } else {
                return jsonReturn.returnFailed("用户信息更新失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("更新用户信息时发生错误：" + e.getMessage());
        }
    }

    // 查询所有用户
    @RequestMapping("/user/list")
    public String list(String nickname){
        try{
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(!ObjectUtils.isEmpty(nickname),User::getNickname, nickname)
                    .eq(User::getIsDeleted, 0);
            List<User> list = userService.list(queryWrapper);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    // 根据id查询用户
    @RequestMapping("/user/listById")
    public String listById(Integer id){
        try{
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getId, id);
            List<User> list = userService.list(queryWrapper);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}